<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML文本提取器 - Web & API 版</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/github.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/languages/xml.min.js"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
            min-height: 80vh;
        }
        
        header {
            grid-column: 1 / -1;
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eaeaea;
        }
        
        h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        .description {
            color: #7f8c8d;
            font-size: 16px;
            max-width: 800px;
            margin: 0 auto;
        }
        
        .api-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0 10px 0;
            grid-column: 1 / -1;
            font-size: 14px;
        }
        
        .api-info h3 {
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 16px;
        }
        
        .api-info pre {
            background: rgba(255, 255, 255, 0.1);
            padding: 8px;
            border-radius: 4px;
            overflow-x: auto;
            margin: 8px 0;
            font-size: 12px;
            line-height: 1.4;
        }
        
        .api-info p {
            margin: 6px 0;
            font-size: 13px;
        }
        
        .api-header {
            cursor: pointer;
            user-select: none;
        }
        
        .api-header:hover {
            opacity: 0.8;
        }
        
        .toggle-icon {
            font-size: 12px;
            transition: transform 0.3s ease;
        }
        
        .api-content {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .input-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        textarea, input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        textarea:focus, input[type="text"]:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        
        textarea {
            min-height: 200px;
            resize: vertical;
            font-family: monospace;
        }
        
        .selector-input {
            font-family: monospace;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 20px;
            font-size: 16px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 600;
        }
        
        button:hover {
            background-color: #2980b9;
        }
        
        button.secondary {
            background-color: #7f8c8d;
        }
        
        button.secondary:hover {
            background-color: #636e70;
        }
        
        button.success {
            background-color: #27ae60;
        }
        
        button.success:hover {
            background-color: #219653;
        }
        
        button.api {
            background-color: #9b59b6;
        }
        
        button.api:hover {
            background-color: #8e44ad;
        }
        
        .result-container {
            margin-top: 20px;
        }
        
        .error {
            color: #e74c3c;
            padding: 10px;
            background-color: #fadbd8;
            border-radius: 5px;
            margin-top: 10px;
            display: none;
        }
        
        .success {
            color: #27ae60;
            padding: 10px;
            background-color: #d5f4e6;
            border-radius: 5px;
            margin-top: 10px;
            display: none;
        }
        
        .examples {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            border-left: 4px solid #3498db;
            margin-top: 20px;
        }
        
        .examples h3 {
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        .examples p {
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .examples code {
            background-color: #eee;
            padding: 2px 5px;
            border-radius: 3px;
            font-family: monospace;
        }
        
        footer {
            grid-column: 1 / -1;
            text-align: center;
            margin-top: 30px;
            color: #7f8c8d;
            font-size: 14px;
        }
        
        /* HTML格式化区域样式 */
        .html-editor {
            position: relative;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
        }
        
        .html-editor textarea {
            min-height: 300px;
            padding: 15px;
            border: none;
            line-height: 1.5;
        }
        
        .editor-header {
            background-color: #f8f9fa;
            padding: 8px 15px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .editor-header h3 {
            font-size: 14px;
            color: #495057;
            margin: 0;
        }
        
        .editor-actions {
            display: flex;
            gap: 8px;
        }
        
        .editor-actions button {
            padding: 6px 12px;
            font-size: 14px;
        }
        
        /* 语法高亮区域 */
        .highlight-container {
            position: relative;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
        }
        
        .highlight-content {
            position: relative;
            height: 300px;
            overflow: auto;
        }
        
        .line-numbers {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            padding: 15px 5px;
            background-color: #f8f9fa;
            border-right: 1px solid #dee2e6;
            text-align: right;
            font-family: monospace;
            color: #6c757d;
            line-height: 1.5;
            overflow: hidden;
            z-index: 1;
        }
        
        .code-container {
            margin-left: 40px;
            overflow: auto;
            height: 100%;
        }
        
        pre {
            margin: 0;
            padding: 15px;
            min-height: 100%;
            overflow: auto;
        }
        
        code {
            font-family: 'Fira Code', monospace;
            font-size: 14px;
        }
        
        /* 选择器历史区域 */
        .selector-history {
            margin-top: 15px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #e9ecef;
        }
        
        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .history-header h3 {
            font-size: 16px;
            color: #2c3e50;
            margin: 0;
        }
        
        .history-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .history-item {
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 20px;
            padding: 6px 12px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
            font-family: monospace;
        }
        
        .history-item:hover {
            background-color: #3498db;
            color: white;
            border-color: #3498db;
        }
        
        .history-item.active {
            background-color: #2c3e50;
            color: white;
            border-color: #2c3e50;
        }
        
        .no-history {
            color: #6c757d;
            font-style: italic;
            text-align: center;
            padding: 10px;
        }
        
        /* 输出选项 */
        .output-options {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        
        .output-options label {
            margin-bottom: 0;
            font-weight: normal;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        /* 表格样式 */
        .table-container {
            margin-top: 15px;
            overflow: auto;
            max-height: 400px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-family: monospace;
            font-size: 14px;
        }
        
        .data-table th {
            background-color: #f8f9fa;
            padding: 10px;
            text-align: left;
            border-bottom: 2px solid #dee2e6;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .data-table td {
            padding: 8px 10px;
            border-bottom: 1px solid #dee2e6;
            vertical-align: top;
        }
        
        .data-table tr:hover {
            background-color: #f8f9fa;
        }
        
        .table-actions {
            margin-top: 10px;
            display: flex;
            gap: 10px;
        }
        
        /* 结果区域样式优化 */
        .result-section {
            display: flex;
            flex-direction: column;
            gap: 10px;
            width: 100%;
            height: 100%;
            overflow: auto;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
        
        .result-section .input-group {
            margin-bottom: 0;
        }
        
        .result-section textarea {
            min-height: 150px;
            max-height: 300px;
            background-color: white;
        }
        
        .result-section .highlight-container {
            flex: 1;
            min-height: 300px;
        }
        
        .result-section .examples {
            margin-top: 0;
        }
        
        /* API测试区域 */
        .api-test {
            background-color: #e8f4f8;
            padding: 15px;
            border-radius: 5px;
            border-left: 4px solid #3498db;
            margin-top: 20px;
        }
        
        .api-test h3 {
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        /* 响应式布局 */
        @media (max-width: 900px) {
            .container {
                grid-template-columns: 1fr;
                min-height: auto;
            }
            
            .history-list {
                flex-direction: column;
            }
            
            .history-item {
                width: 100%;
                text-align: center;
            }
            
            .button-group {
                flex-wrap: wrap;
            }
            
            .button-group button {
                flex: 1;
                min-width: 120px;
            }
            
            .result-section {
                height: auto;
                min-height: 500px;
            }
        }
        
        /* 滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 状态指示器 */
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-saved {
            background-color: #27ae60;
        }
        
        .status-unsaved {
            background-color: #e74c3c;
        }
        
        .tab-container {
            margin-top: 15px;
        }
        
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 15px;
        }
        
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            border-bottom: none;
            background: #f8f9fa;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
        }
        
        .tab.active {
            background: white;
            border-color: #ddd;
            border-bottom-color: white;
            margin-bottom: -1px;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        /* 帮助文本样式 */
        .help-text {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>HTML文本提取器 - Web & API 版</h1>
            <p class="description">支持Web界面和HTTP API两种方式提取HTML内容</p>
        </header>
        
        
        <div class="input-section">
            <div class="input-group">
                <label for="html-input">
                    <span class="status-indicator status-saved" id="html-status"></span>
                    HTML源代码：
                </label>
                <div class="html-editor">
                    <div class="editor-header">
                        <h3>HTML编辑器 (自动保存)</h3>
                        <div class="editor-actions">
                            <button id="format-btn" class="secondary">格式化</button>
                            <button id="clear-btn" class="secondary">清除</button>
                        </div>
                    </div>
                    <textarea id="html-input" placeholder="请输入HTML代码或片段..."></textarea>
                </div>
            </div>
            
            <div class="input-group">
                <label for="selector-input">
                    <span class="status-indicator status-saved" id="selector-status"></span>
                    jQuery选择器（多个用 | 分隔）：
                </label>
                <input type="text" id="selector-input" class="selector-input" placeholder="例如：td:nth-child(1) | td:nth-child(2) | td:nth-child(3)">
            </div>
            
            <div class="input-group">
                <label for="attribute-input">
                    <span class="status-indicator status-saved" id="attribute-status"></span>
                    属性名（可选，多个用 | 分隔）：
                </label>
                <input type="text" id="attribute-input" class="selector-input" placeholder="例如：src, href, title, data-id">
                <div class="help-text">留空则提取文本内容，填写属性名则提取属性值</div>
            </div>
            
            <div class="input-group">
                <label>
                    <input type="checkbox" id="extract-both" checked> 同时提取属性和文本
                </label>
                <div class="help-text">勾选后，每个元素会同时提取属性值和文本内容</div>
            </div>
            
            <div class="output-options">
                <label>
                    <input type="checkbox" id="table-format">
                    输出表格格式
                </label>
                <span id="table-info" style="color: #6c757d; font-size: 14px;"></span>
            </div>
            
            <div class="selector-history">
                <div class="history-header">
                    <h3>最近使用的选择器</h3>
                    <button id="clear-history-btn" class="secondary" style="padding: 4px 8px; font-size: 12px;">清除历史</button>
                </div>
                <div id="history-list" class="history-list">
                    <div class="no-history">暂无历史记录</div>
                </div>
            </div>
            
            <div class="button-group">
                <button id="extract-btn" style="flex: 2;">提取文本</button>
                <button id="example-btn">加载示例</button>
                <button id="save-selector-btn" class="success">保存选择器</button>
                <button id="api-test-btn" class="api">测试API</button>
            </div>
            
            <div id="error-message" class="error"></div>
            <div id="success-message" class="success"></div>
            
            <div class="api-test">
                <h3>🔧 API 测试</h3>
                <button id="generate-curl-btn" class="secondary">生成cURL命令</button>
                <div id="curl-command" style="display: none; margin-top: 10px; background: #2c3e50; color: white; padding: 10px; border-radius: 5px; font-family: monospace; font-size: 12px;"></div>
            </div>
        </div>
        
        <div class="result-section">
            <div class="tabs">
                <div class="tab active" data-tab="result">提取结果</div>
                <div class="tab" data-tab="preview">HTML预览</div>
                <div class="tab" data-tab="api-response">API响应</div>
            </div>
            
            <div class="tab-content active" id="result-tab">
                <div class="input-group">
                    <label for="result">文本结果：</label>
                    <textarea id="result" readonly placeholder="提取结果将显示在这里..."></textarea>
                </div>
                
                <div id="table-output" class="table-container" style="display: none;">
                    <table class="data-table">
                        <thead>
                            <tr id="table-headers"></tr>
                        </thead>
                        <tbody id="table-body"></tbody>
                    </table>
                    <div class="table-actions">
                        <button id="copy-table-btn" class="success">复制表格</button>
                        <button id="export-csv-btn" class="secondary">导出CSV</button>
                    </div>
                </div>
            </div>
            
            <div class="tab-content" id="preview-tab">
                <div class="input-group">
                    <label>HTML预览（带语法高亮）：</label>
                    <div class="highlight-container">
                        <div class="highlight-content">
                            <div class="line-numbers"></div>
                            <div class="code-container">
                                <pre><code class="language-html" id="html-preview"></code></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="tab-content" id="api-response-tab">
                <div class="input-group">
                    <label for="api-response">API响应JSON：</label>
                    <textarea id="api-response" readonly placeholder="API响应将显示在这里..." style="min-height: 300px; font-family: monospace;"></textarea>
                </div>
            </div>
            
            <div class="examples">
                <h3>使用示例：</h3>
                <p>• 提取表格多列：<code>td:nth-child(1) | td:nth-child(2) | td:nth-child(3)</code></p>
                <p>• 提取商品信息：<code>.product-name | .price | .brand</code></p>
                <p>• 提取链接和文本：<code>a | a@href</code>（支持属性选择器）</p>
                <p>• 提取标题和描述：<code>h2 | .description</code></p>
                <p>• 多个类名选择：<code>.item .name | .item .value</code></p>
                <p>• <strong>同时提取属性和文本</strong>：选择器 <code>a | img</code>，属性 <code>href | src</code>，勾选"同时提取属性和文本"</p>
                <p>• 提取图片链接和alt文本：选择器 <code>img</code>，属性 <code>src</code>，勾选"同时提取属性和文本"</p>
            </div>
        </div>
        
        <div class="api-info">
            <div class="api-header" onclick="toggleApiInfo()">
                <h3>📡 HTTP API 端点 <span class="toggle-icon">▼</span></h3>
            </div>
            <div class="api-content" id="api-content" style="display: none;">
                <p>POST <code>/api/extract</code> - 提取HTML内容</p>
                <pre>{
  "html": "&lt;div&gt;示例HTML内容&lt;/div&gt;",
  "selector": "div | span",
  "attribute": "href | src",
  "extractBoth": true,
  "tableFormat": false
}</pre>
                <p>响应格式：</p>
                <pre>{
  "success": true,
  "data": ["提取结果1", "提取结果2"],
  "tableData": [["行1列1", "行1列2"], ["行2列1", "行2列2"]]
}</pre>
            </div>
        </div>
        
        <footer>
            <p>HTML文本提取器 - Web & API 版 &copy; 2023 | 已保存 <span id="history-count">0</span> 个选择器</p>
        </footer>
    </div>

    <script>
        $(document).ready(function() {
            // 初始化高亮显示
            hljs.highlightAll();
            
            // 选择器历史存储
            let selectorHistory = JSON.parse(localStorage.getItem('selectorHistory')) || [];
            
            // 加载保存的内容
            const savedHtml = localStorage.getItem('savedHtml');
            const savedSelector = localStorage.getItem('savedSelector');
            const savedAttribute = localStorage.getItem('savedAttribute');
            const savedExtractBoth = localStorage.getItem('savedExtractBoth') === 'true';
            const savedTableFormat = localStorage.getItem('savedTableFormat') === 'true';
            
            if (savedHtml) {
                $('#html-input').val(savedHtml);
                updateStatus('html-status', true);
            }
            
            if (savedSelector) {
                $('#selector-input').val(savedSelector);
                updateStatus('selector-status', true);
            }
            
            if (savedAttribute) {
                $('#attribute-input').val(savedAttribute);
                updateStatus('attribute-status', true);
            }
            
            if (savedExtractBoth) {
                $('#extract-both').prop('checked', true);
            }
            
            if (savedTableFormat) {
                $('#table-format').prop('checked', true);
            }
            
            // 标签切换
            $('.tab').click(function() {
                const tabName = $(this).data('tab');
                $('.tab').removeClass('active');
                $(this).addClass('active');
                $('.tab-content').removeClass('active');
                $(`#${tabName}-tab`).addClass('active');
            });
            
            // 更新状态指示器
            function updateStatus(elementId, isSaved) {
                const $indicator = $('#' + elementId);
                $indicator.removeClass('status-saved status-unsaved');
                $indicator.addClass(isSaved ? 'status-saved' : 'status-unsaved');
            }
            
            // 保存内容到本地存储
            function saveToLocalStorage() {
                const htmlContent = $('#html-input').val();
                const selector = $('#selector-input').val();
                const attribute = $('#attribute-input').val();
                const extractBoth = $('#extract-both').is(':checked');
                const tableFormat = $('#table-format').is(':checked');
                
                localStorage.setItem('savedHtml', htmlContent);
                localStorage.setItem('savedSelector', selector);
                localStorage.setItem('savedAttribute', attribute);
                localStorage.setItem('savedExtractBoth', extractBoth);
                localStorage.setItem('savedTableFormat', tableFormat);
                
                updateStatus('html-status', true);
                updateStatus('selector-status', true);
                updateStatus('attribute-status', true);
            }
            
            // 自动保存功能
            let saveTimeout;
            function scheduleSave() {
                clearTimeout(saveTimeout);
                saveTimeout = setTimeout(saveToLocalStorage, 1000);
                updateStatus('html-status', false);
                updateStatus('selector-status', false);
                updateStatus('attribute-status', false);
            }
            
            // 更新历史显示
            function updateHistoryDisplay() {
                const historyList = $('#history-list');
                historyList.empty();
                
                if (selectorHistory.length === 0) {
                    historyList.append('<div class="no-history">暂无历史记录</div>');
                } else {
                    selectorHistory.forEach((selector, index) => {
                        historyList.append(`<div class="history-item" data-selector="${selector}">${selector}</div>`);
                    });
                }
                
                $('#history-count').text(selectorHistory.length);
            }
            
            // 保存选择器到历史
            function saveSelectorToHistory(selector) {
                if (!selector.trim()) return;
                
                // 移除重复的选择器
                selectorHistory = selectorHistory.filter(s => s !== selector);
                
                // 添加到开头
                selectorHistory.unshift(selector);
                
                // 限制最多10个
                if (selectorHistory.length > 10) {
                    selectorHistory = selectorHistory.slice(0, 10);
                }
                
                // 保存到localStorage
                localStorage.setItem('selectorHistory', JSON.stringify(selectorHistory));
                
                // 更新显示
                updateHistoryDisplay();
                
                // 显示成功消息
                showSuccess('选择器已保存到历史记录');
            }
            
            // 更新行号和预览
            function updatePreview() {
                const htmlContent = $('#html-input').val();
                $('#html-preview').text(htmlContent);
                hljs.highlightElement(document.getElementById('html-preview'));
                
                // 更新行号
                const lineCount = htmlContent.split('\n').length;
                let lineNumbers = '';
                for (let i = 1; i <= lineCount; i++) {
                    lineNumbers += i + '<br>';
                }
                $('.line-numbers').html(lineNumbers);
            }
            
            // HTML格式化函数
            function formatHtml(html) {
                const tab = '    ';
                let result = '';
                let indent = '';
                
                html.split(/>\s*</).forEach(function(element) {
                    if (element.match(/^\/\w/)) {
                        indent = indent.substring(tab.length);
                    }
                    
                    result += indent + '<' + element + '>\r\n';
                    
                    if (element.match(/^<?\w[^>]*[^\/]$/) && !element.startsWith('input')) { 
                        indent += tab;
                    }
                });
                
                return result.substring(1, result.length - 3);
            }
            
            // 提取属性值（支持选择器如 a@href）
            function extractAttribute($element, selector) {
                if (selector.includes('@')) {
                    const parts = selector.split('@');
                    const elementSelector = parts[0];
                    const attrName = parts[1];
                    const $target = elementSelector ? $element.find(elementSelector).first() : $element;
                    return $target.attr(attrName) || '';
                }
                return $element.text().trim();
            }
            
            // 格式化按钮点击事件
            $('#format-btn').click(function() {
                try {
                    const htmlContent = $('#html-input').val();
                    const formattedHtml = formatHtml(htmlContent);
                    $('#html-input').val(formattedHtml);
                    updatePreview();
                    scheduleSave();
                    showSuccess('HTML格式化完成');
                } catch (error) {
                    showError('格式化HTML时出错: ' + error.message);
                }
            });
            
            // 清除按钮点击事件
            $('#clear-btn').click(function() {
                $('#html-input').val('');
                updatePreview();
                scheduleSave();
                showSuccess('内容已清除');
            });
            
            // 清除历史按钮点击事件
            $('#clear-history-btn').click(function() {
                selectorHistory = [];
                localStorage.removeItem('selectorHistory');
                updateHistoryDisplay();
                showSuccess('历史记录已清除');
            });
            
            // 保存选择器按钮点击事件
            $('#save-selector-btn').click(function() {
                const selector = $('#selector-input').val().trim();
                if (selector) {
                    saveSelectorToHistory(selector);
                } else {
                    showError('请输入有效的选择器');
                }
            });
            
            // 历史项点击事件
            $(document).on('click', '.history-item', function() {
                const selector = $(this).data('selector');
                $('#selector-input').val(selector);
                $('.history-item').removeClass('active');
                $(this).addClass('active');
                scheduleSave();
            });
            
            // 表格格式复选框事件
            $('#table-format').change(function() {
                scheduleSave();
            });
            
            // 复制表格按钮事件
            $('#copy-table-btn').click(function() {
                const tableText = $('#table-body tr').map(function() {
                    return $(this).find('td').map(function() {
                        return $(this).text();
                    }).get().join('\t');
                }).get().join('\n');
                
                navigator.clipboard.writeText(tableText).then(function() {
                    showSuccess('表格已复制到剪贴板，可直接粘贴到Excel中');
                }).catch(function() {
                    showError('复制失败，请手动选择复制');
                });
            });
            
            // 导出CSV按钮事件
            $('#export-csv-btn').click(function() {
                const headers = $('#table-headers th').map(function() {
                    return $(this).text();
                }).get();
                
                const rows = $('#table-body tr').map(function() {
                    return $(this).find('td').map(function() {
                        return '"' + $(this).text().replace(/"/g, '""') + '"';
                    }).get().join(',');
                }).get();
                
                const csvContent = [headers.join(','), ...rows].join('\n');
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                
                link.setAttribute('href', url);
                link.setAttribute('download', 'extracted_data.csv');
                link.style.visibility = 'hidden';
                
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                showSuccess('CSV文件已下载');
            });
            
            // 生成cURL命令
            $('#generate-curl-btn').click(function() {
                const htmlContent = $('#html-input').val();
                const selector = $('#selector-input').val();
                const attribute = $('#attribute-input').val();
                const extractBoth = $('#extract-both').is(':checked');
                const tableFormat = $('#table-format').is(':checked');
                
                const jsonData = JSON.stringify({
                    html: htmlContent,
                    selector: selector,
                    attribute: attribute,
                    extractBoth: extractBoth,
                    tableFormat: tableFormat
                }, null, 2);
                
                const curlCommand = `curl -X POST http://localhost:3000/api/extract \\
  -H "Content-Type: application/json" \\
  -d '${jsonData.replace(/\n/g, '\\n').replace(/'/g, "\\'")}'`;
                
                $('#curl-command').text(curlCommand).show();
            });
            
            // API测试按钮事件
            $('#api-test-btn').click(function() {
                const htmlContent = $('#html-input').val();
                const selector = $('#selector-input').val();
                const attribute = $('#attribute-input').val();
                const extractBoth = $('#extract-both').is(':checked');
                const tableFormat = $('#table-format').is(':checked');
                
                if (!htmlContent.trim()) {
                    showError('请输入HTML代码');
                    return;
                }
                
                if (!selector.trim()) {
                    showError('请输入jQuery选择器');
                    return;
                }
                
                // 显示加载中
                showSuccess('正在调用API...');
                
                // 调用API
                fetch('/api/extract', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        html: htmlContent,
                        selector: selector,
                        attribute: attribute,
                        extractBoth: extractBoth,
                        tableFormat: tableFormat
                    })
                })
                .then(response => response.json())
                .then(data => {
                    $('#api-response').val(JSON.stringify(data, null, 2));
                    $('.tab[data-tab="api-response"]').click();
                    showSuccess('API调用成功');
                })
                .catch(error => {
                    showError('API调用失败: ' + error.message);
                });
            });
            
            // 示例按钮点击事件
            $('#example-btn').click(function() {
                const exampleHtml = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品展示示例</title>
    <style>
        .product-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            margin: 20px;
            max-width: 300px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
        }
        .product-title {
            font-size: 18px;
            font-weight: bold;
            margin: 10px 0;
            color: #333;
        }
        .product-link {
            color: #007bff;
            text-decoration: none;
            font-weight: 500;
        }
        .product-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="product-card">
        <img src="https://via.placeholder.com/300x200/4CAF50/FFFFFF?text=示例商品图片" 
             alt="商品图片" 
             class="product-image">
        <h3 class="product-title">优质商品标题</h3>
        <a href="https://example.com/product/123" 
           class="product-link" 
           target="_blank">
            查看商品详情
        </a>
    </div>
    
    <div class="product-card">
        <img src="https://via.placeholder.com/300x200/2196F3/FFFFFF?text=另一个商品" 
             alt="另一个商品图片" 
             class="product-image">
        <h3 class="product-title">另一个商品标题</h3>
        <a href="https://example.com/product/456" 
           class="product-link" 
           target="_blank">
            立即购买
        </a>
    </div>
</body>
</html>`;
                
                $('#html-input').val(exampleHtml);
                $('#selector-input').val('a | img');
                $('#attribute-input').val('href | src');
                $('#extract-both').prop('checked', true);
                updatePreview();
                scheduleSave();
                showSuccess('示例代码已加载，展示了同时提取属性和文本的功能');
            });
            
            // 提取按钮点击事件
            $('#extract-btn').click(function() {
                // 隐藏之前的消息
                $('#error-message').hide();
                $('#success-message').hide();
                
                // 获取输入的值
                const htmlContent = $('#html-input').val();
                const selectorInput = $('#selector-input').val();
                const attributeInput = $('#attribute-input').val();
                const extractBoth = $('#extract-both').is(':checked');
                const isTableFormat = $('#table-format').is(':checked');
                
                // 验证输入
                if (!htmlContent.trim()) {
                    showError('请输入HTML代码');
                    return;
                }
                
                if (!selectorInput.trim()) {
                    showError('请输入jQuery选择器');
                    return;
                }
                
                try {
                    // 分割多个选择器
                    const selectors = selectorInput.split('|').map(s => s.trim()).filter(s => s);
                    
                    // 分割多个属性（如果提供了）
                    const attributes = attributeInput ? attributeInput.split('|').map(a => a.trim()).filter(a => a) : [];
                    
                    // 确保选择器和属性数量匹配（除非是同时提取模式）
                    if (attributes.length > 0 && attributes.length !== selectors.length && !extractBoth) {
                        showError('选择器和属性数量必须匹配');
                        return;
                    }
                    
                    // 创建临时DOM元素来解析HTML
                    const $tempContainer = $('<div>').html(htmlContent);
                    
                    let results = [];
                    
                    if (extractBoth) {
                        // 同时提取属性和文本模式
                        results = selectors.map((selector, index) => {
                            const elements = $tempContainer.find(selector);
                            return elements.map(function() {
                                const $element = $(this);
                                const attrValue = attributes[index] ? ($element.attr(attributes[index]) || '') : '';
                                const textValue = $element.text().trim();
                                return `${attrValue}\t${textValue}`;
                            }).get();
                        });
                    } else {
                        // 原有模式：要么提取属性，要么提取文本
                        results = selectors.map((selector, index) => {
                            const elements = $tempContainer.find(selector);
                            return elements.map(function() {
                                const $element = $(this);
                                if (attributes.length > 0 && attributes[index]) {
                                    // 提取属性值
                                    return $element.attr(attributes[index]) || '';
                                } else {
                                    // 提取文本内容
                                    return $element.text().trim();
                                }
                            }).get();
                        });
                    }
                    
                    // 检查是否有结果
                    if (results.some(arr => arr.length === 0)) {
                        showError('某些选择器没有找到匹配的元素。请检查选择器是否正确。');
                        return;
                    }
                    
                    // 检查所有结果长度是否一致
                    const lengths = results.map(arr => arr.length);
                    const maxLength = Math.max(...lengths);
                    const minLength = Math.min(...lengths);
                    
                    if (maxLength !== minLength) {
                        showError(`警告：选择器返回的结果数量不一致（${lengths.join(', ')}）。表格可能不完整。`);
                    }
                    
                    if (isTableFormat) {
                        // 显示表格格式
                        displayTableResults(results, selectors);
                    } else {
                        // 显示文本格式
                        displayTextResults(results, selectors);
                    }
                    
                    // 自动保存选择器到历史
                    saveSelectorToHistory(selectorInput);
                    
                    let extractType = '数据';
                    if (extractBoth) {
                        extractType = '属性和文本数据';
                    } else if (attributes.length > 0) {
                        extractType = '属性数据';
                    } else {
                        extractType = '文本数据';
                    }
                    showSuccess(`成功提取了 ${maxLength} 行${extractType}`);
                    
                } catch (error) {
                    showError('提取过程中发生错误: ' + error.message);
                }
            });
            
            // 显示表格结果
            function displayTableResults(results, selectors) {
                const $tableHeaders = $('#table-headers');
                const $tableBody = $('#table-body');
                
                $tableHeaders.empty();
                $tableBody.empty();
                
                // 添加表头
                selectors.forEach((selector, index) => {
                    $tableHeaders.append(`<th>列 ${index + 1}</th>`);
                });
                
                // 添加表格数据
                const rowCount = Math.max(...results.map(arr => arr.length));
                for (let i = 0; i < rowCount; i++) {
                    const $row = $('<tr>');
                    selectors.forEach((selector, colIndex) => {
                        const value = results[colIndex][i] || '';
                        $row.append(`<td>${value}</td>`);
                    });
                    $tableBody.append($row);
                }
                
                // 更新表格信息
                $('#table-info').text(`${rowCount} 行 × ${selectors.length} 列`);
                $('#table-output').show();
            }
            
            // 显示文本结果
            function displayTextResults(results, selectors) {
                let resultText = '';
                const rowCount = Math.max(...results.map(arr => arr.length));
                
                for (let i = 0; i < rowCount; i++) {
                    let rowText = '';
                    selectors.forEach((selector, colIndex) => {
                        const value = results[colIndex][i] || '';
                        rowText += value + '\t';
                    });
                    resultText += rowText.trim() + '\n';
                }
                
                $('#result').val(resultText.trim());
                $('#table-output').hide();
            }
            
            // 输入框变化时自动保存
            $('#html-input').on('input', function() {
                updatePreview();
                scheduleSave();
            });
            
            $('#selector-input').on('input', function() {
                scheduleSave();
            });
            
            $('#attribute-input').on('input', function() {
                scheduleSave();
            });
            
            $('#extract-both').on('change', function() {
                scheduleSave();
            });
            
            function showError(message) {
                $('#error-message').text(message).show();
                $('#success-message').hide();
                $('#result').val('');
            }
            
            function showSuccess(message) {
                $('#success-message').text(message).show();
                $('#error-message').hide();
                setTimeout(() => {
                    $('#success-message').fadeOut();
                }, 3000);
            }
            
            // 初始化
            updatePreview();
            updateHistoryDisplay();
            
            // 页面卸载前保存
            $(window).on('beforeunload', function() {
                saveToLocalStorage();
            });
        });
        
        // API信息展开/折叠功能
        function toggleApiInfo() {
            const content = document.getElementById('api-content');
            const icon = document.querySelector('.toggle-icon');
            
            if (content.style.display === 'none') {
                content.style.display = 'block';
                icon.textContent = '▲';
                icon.style.transform = 'rotate(0deg)';
            } else {
                content.style.display = 'none';
                icon.textContent = '▼';
                icon.style.transform = 'rotate(0deg)';
            }
        }
    </script>
</body>
</html>
